/*
 * Copyright 2020 DuJiang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rc.saas.tenant.crypto.util;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import com.rc.saas.tenant.crypto.exception.RestCryptoException;

/**
 * KeyUtils
 * 
 * @author DuJiang
 */
public final class KeyUtils {

	/**
	 * String转公钥PublicKey
	 * @param algorithm
	 * @param key
	 * @return PublicKey
	 * @throws RestCryptoException 
	 */
	public static final PublicKey getPublicKey(final String algorithm, final String key) throws RestCryptoException {
		try {
			byte[] keyBytes = Base64.getDecoder().decode(key);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
			return KeyFactory.getInstance(algorithm).generatePublic(keySpec);
		} catch (Exception e) {
			throw new RestCryptoException("generate public key exception", e);
		}
	}

	/**
	 * String转私钥PrivateKey
	 * @param algorithm
	 * @param key
	 * @return PrivateKey
	 * @throws RestCryptoException 
	 */
	public static final PrivateKey getPrivateKey(final String algorithm, final String key) throws RestCryptoException {
		try {
			byte[] keyBytes = Base64.getDecoder().decode(key);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
			return KeyFactory.getInstance(algorithm).generatePrivate(keySpec);
		} catch (Exception e) {
			throw new RestCryptoException("generate private key exception", e);
		}
	}

	/**
	 * 生成加密秘钥
	 * @param algorithm
	 * @param keySize
	 * @param key
	 * @return SecretKey
	 */
	public static final SecretKey getSecretKey(final String algorithm, final int keySize, final String key) {
		try {
			KeyGenerator kg = KeyGenerator.getInstance(algorithm);
			kg.init(keySize, new SecureRandom(key.getBytes()));
			return kg.generateKey();
		} catch (Exception e) {
			throw new RestCryptoException("generate Secretkey exception", e);
		}
	}

}